package com.lg.system;

import java.sql.*;
import java.util.*;

import javax.servlet.http.*;
import com.base.*;



public class CDataPageBase implements java.io.Serializable{

	private int mCurPage = 0; //初始化当前的页
	  private int mPageRowCount = 10; //初始化每页显示的行数
	  private ArrayList mList = new ArrayList();
	  private int mTotalPage = 0; //定义总共的页数
	  private int mTotalRowCount = 0; //定义总共的记录数
	  private static final String BLANK = "   ";
	  private String mTurnPageStr = ""; //最后的翻页代码
	  private String mCssClass = DEFAULT_CSS_NAME; //CSS控制类名称
	  private String mQuerySql = ""; //查询的SQL语句
	  private String mFormName = "DataListForm";  // Form 的名字
	  private String mSelectColor = "#FBE3B2";
	  private static final String DEFAULT_SELECT_COLOR = "#FBE3B2";
	  /**起始页的地址*/
	  public static final int PAGE_FIRST = 1;
	  private static final String DEFAULT_CSS_NAME = "td_Page";
	  private static final String DEFAULT_CHANGE_PAGE_NAME = "changePage";
	  public String percent="100%";
	  public String selectCss="page";
	  //获取总数的SQL;
	  private String mCountSQL = "";
	  private String orderStr;
	  private String queryFormOrderColumn;
	  /**
	   * 构造函数
	   */
	  public CDataPageBase()throws Exception {
	  }

//	  public CDataPageBase(Connection pConn)throws Exception {
//	    mConn=pConn;
//	  }
	  /**
	   * 设置当前页面为第几页
	   * @param pCurpage
	   */
	  public void setCurPage(int pCurpage) {
	    mCurPage = pCurpage;
	  }

	  /**
	   * 设置当前CSS控制类名
	   * @param pCssClass
	   */
	  public void setCssClass(String pCssClass) {
	    mCssClass = pCssClass;
	  }

	  /**
	   * 取当前CSS控制类名
	   */
	  public String getCssClass() {
	    return mCssClass;
	  }

	  /**
	   * 设置当前查询的SQL语句
	   * @param pQuerySql
	   */
	  public void setQuerySql(String pQuerySql) {
	    mQuerySql = pQuerySql;
	  }

	  /**
	   * 取当前查询的SQL语句
	   */
	  public String getQuerySql() {
	    return mQuerySql;
	  }

	  public void setSelectColor(String pSelectColor) {
	    mSelectColor = pSelectColor;
	  }

	  public String getSelectColor() {
	    return mSelectColor;
	  }

	  /**
	   * 获取当前页面
	   * @return 当前页面
	   */
	  public int getCurPage() {
	    return mCurPage;
	  }

	  /**
	   * 获取最后的翻页代码
	   * @return 当前页面
	   */
//	  public String getTurnPageStr() {
//	    mTurnPageStr = printTurnPage();
//	    return mTurnPageStr;
//	  }

	  /**
	   * 设置一页显示的行数
	   * @param pPageRowCount 传入行数
	   */
	  public void setPageRowCount(int pPageRowCount) {
	    mPageRowCount = pPageRowCount;
	  }

	  /**
	   * 获取一页显示的行数
	   * @return 一页显示的行数
	   */
	  public int getPageRowCount() {
	    return mPageRowCount;
	  }

	  /**
	   * 获取总页数
	   * @return 总页数
	   */
	  public int getTotalPage() {
	    return mTotalPage;
	  }

	  /**
	   * 获取总纪录数
	   * @return 总纪录数
	   */
	  public int getTotalRowCount() {
	    return mTotalRowCount;
	  }

	  /**
	   * 初始化翻页控件，必须先设置查询的SQL语句。
	   * @param pRequest
	   * @return
	   */
	  public void init(HttpServletRequest pRequest) throws Exception{
	    getArrayListData(pRequest, mQuerySql);
	  }

	  /**
	   * 通过sql语句查询获取当前页面纪录的ArrayList聚合
	   * @param pRequest
	   * @param pSql
	   * @return
	   */
	  public ArrayList getArrayListData(HttpServletRequest pRequest, String pSql) throws Exception{
	    String aFormName = mFormName;
	    aFormName = aFormName.replaceAll("\\[", "");
	    aFormName = aFormName.replaceAll("\\]", "");

	    String curPageNo = pRequest.getParameter("selectpageno" + aFormName);
	    if (curPageNo == null || curPageNo.length() < 1) {
	      this.setCurPage(PAGE_FIRST);
	    }
	    else {
	      this.setCurPage(Integer.parseInt(curPageNo));
	    }
	    return getVectorData(pSql);
	  }

	  /**
	   * 通过sql语句查询获取当前页面纪录的ArrayList聚合
	   * @param pSql sql语句
	   * @return ArrayList纪录聚合，记录以Properties表示
	   */
	  public ArrayList getVectorData(String pSql) throws Exception{
	    Connection mConn = null;
	    String checkSql=pSql.trim().toUpperCase();
	    //限制只能运行SELECT语句
	    if (!checkSql.substring(0,6).equals("SELECT")) {
	      return null;
	    }

//	    int index = checkSql.indexOf("FROM");
//	    mCountSQL = "select count(*)   " + pSql.substring(index);
	    if (mCountSQL.length() < 1){  // 没有定义计数的SQL，则生成
	      mCountSQL = "select count(1) from (" + pSql + ")";
	    }

	    ResultSet mRs = null;
	    Statement mStmt = null;
	    try {
	      mConn = CDBManager.getConn();
	      // edit by chenwj 2004-12-23
	      mStmt = mConn.createStatement();
//	      mPs = this.mConn.prepareStatement(mCountSQL, ResultSet.TYPE_SCROLL_INSENSITIVE,
//	                                        ResultSet.CONCUR_READ_ONLY);
	      BaseLog.logger.info("countSQL = " + mCountSQL);
	      mRs = mStmt.executeQuery(mCountSQL);
	      if (mRs.next()) {

	        this.mTotalRowCount = mRs.getInt(1);
	        if (this.mPageRowCount == 0) {
	        }
	        else {
	          this.mTotalPage = (int) ( (mTotalRowCount + mPageRowCount - 1) /
	                                   mPageRowCount);
	        }
	      }
	      mRs.close();
	      // add by chenwj 2005-03-28
	      mStmt.close();
	      // add end
	      // edit by chenwj 2004-12-23
//	      mPs.close();
//	      mPs = this.mConn.prepareStatement(pSql, ResultSet.TYPE_SCROLL_INSENSITIVE,
//	                                        ResultSet.CONCUR_READ_ONLY);
//	      mRs = mPs.executeQuery();
	      // edit by chenwj 2005-3-14
	      if (mTotalRowCount < this.mPageRowCount){  // 如果查出来的行数比一页显示的记录还要少，很可能就是进行翻页后输入条件进行查询
	        this.mCurPage = 1;                       // 默认显示第 1 页
	      }
	      int iStartRow = (this.mCurPage - 1) * this.mPageRowCount + 1;
	      int iEndRow = (this.mCurPage) * this.mPageRowCount;
	      if (queryFormOrderColumn != null && queryFormOrderColumn.length() > 0){
	        pSql = pSql + " ORDER BY " + queryFormOrderColumn;
	      }
	      else if (orderStr != null && orderStr.length() > 0){
	        pSql = pSql + " " + orderStr;
	      }
	      pSql = "select * from ( select s.*,rownum id_tj from  (" + pSql +
	        ") s ) where id_tj between " + iStartRow + " and " + iEndRow;

	      // add by chenwj 2005-03-28
	      mStmt = mConn.createStatement();
	      // add end
	      BaseLog.logger.info("querySQL = " + pSql);
	      mRs = mStmt.executeQuery(pSql);
	      this.getVectorData(mRs);
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	    }
	    finally {
//	      CDBOperater.cleanup(mRs, mPs, null);
	      if(mRs!=null) try{mRs.close();} catch(Exception e){}
	      if(mStmt!=null) try{mStmt.close();} catch(Exception e){}
	      if(mConn!=null) mConn.close();
	    }
	    return this.mList;
	  }

	  /**
	   * 通过ResultSet结果集进行相关属性的赋值
	   * @param pRs 传入的结果聚合
	   * @throws SQLException
	   */
	  private void getVectorData(ResultSet pResult) throws SQLException {

	    try {
	      this.mList.clear();
	      //取得所有记录数
	      ResultSetMetaData RsMeta = pResult.getMetaData();
	      Properties item = null;
	      String field = "";
	      int numberOfColumns = RsMeta.getColumnCount();
	      //保存字段名称
	      //当前页面的纪录始末，从1开始计起
	      // 取得当前页面的纪录.
	      this.mList = new ArrayList();
	      Object obj = null;
	      while (pResult.next()) {
	        item = new Properties();
	        for (int i = 1; i <= numberOfColumns; i++) {
	          field = RsMeta.getColumnName(i);
	          String columnType = RsMeta.getColumnTypeName(i);
	          if (columnType.equals("DATE")) {
	            obj = pResult.getTimestamp(i);
	          }else{
	            obj = pResult.getObject(i);
	          }
	          //假如是NULL值，返回空格，否则下面的put方法不支持
	          if (obj == null) {
	            obj = "";
	          }
	          item.put(field, obj);
	        }
	        this.mList.add(item);
	      }
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	    }
	    finally {
	    }
	  }

	  /**
	   * 获取纪录的字段值
	   * @param pRowNum 当前纪录
	   * @param pFieldName 字段名称
	   * @return 字段值Object
	   */

	  public Object getObjectAt(int pRowNum, String pFieldName) {
	    if (mList.isEmpty()) {
	      return null;
	    }
	    else {
	      Properties properties = (Properties) mList.get(pRowNum);
	      return properties.get(pFieldName);
	    }
	  }

	  /**
	   * 获取纪录的字段值
	   * @param pRowNum 当前纪录
	   * @param pFieldName 字段名称
	   * @return 字段值
	   */

	  public String getFieldValue(int pRowNum, String pFieldName) {
	    Object obt = getObjectAt(pRowNum, pFieldName);
	    if (obt == null) {
	      return BLANK;
	    }
	    if (obt instanceof String) {
	      return ( (String) obt).trim();
	    }
	    if (obt instanceof Integer) {
	      return ( (Integer) obt).toString();
	    }
	    if (obt instanceof Timestamp) {
	      return CDateTime.format( (java.sql.Timestamp) obt,
	                              CDateTime.FORMATPAT_SECOND);
	    }
	    if (obt instanceof java.util.Date) {
	      return CDateTime.format( (java.sql.Timestamp) obt,
	                              CDateTime.FORMATPAT_SECOND);
	    }
	     return obt.toString().trim();
	  }

	  /**
	   * 判断当前查询是否为空
	   * @return 假如空返回 true
	   */
	  public boolean isEmpty() {
	    return mList.isEmpty();
	  }
	  /**
	   * 返回mList
	   * @return 假如空返回 true
	   */
	  public ArrayList getMList() {
	    return this.mList;
	  }


	  /**
	   *返回当前页面纪录的大小
	   * @return int size
	   */
	  public int size() {
	    return mList.size();
	  }
	  public void setPercent(String percent) {
	    this.percent = percent;
	  }
	  public void setMCountSQL(String mCountSQL) {
	    this.mCountSQL = mCountSQL;
	  }

	  public void setOrderStr(String orderStr) {
	    this.orderStr = orderStr;
	  }

	  public void setQueryFormOrderColumn(String queryFormOrderColumn) {
	    this.queryFormOrderColumn = queryFormOrderColumn;
	  }

	  public void setFormName(String mFormName){
	    this.mFormName = mFormName;
	  }
	  public String getFormName(){
	    return mFormName;
	  }

	  public String getOrderStr() {
	    return orderStr;
	  }

	  public String getQueryFormOrderColumn() {
	    return queryFormOrderColumn;
	  }
}
